<script setup lang="ts">
import { onMounted } from 'vue';
import { ref } from 'vue';
import httpClient from '../utils/HttpClient'
import type { WordEntity } from 'spen-common/src/entity/WordEntity';
import speechSynthesis from '@/utils/speechSynthesis';
import {FilterResult, wordFilter, type Filter} from '../stores/counter'
import type { Result } from 'spen-common/src/Result';
import {type PageQueryEntity} from 'spen-common/src/Query';
import { ElInput, ElForm, ElFormItem} from 'element-plus';
import { useRoute } from 'vue-router';

const router = useRoute()

const headerInputDiv = ref<HTMLInputElement>();
// 输入框列表
const inputDivList = ref<HTMLInputElement[]>([]);
// 过滤器持久化对象
const filter = wordFilter();

// 当前的单词页
const page = ref<WordEntity[]>();
// 单词所在当前的的第几个
const pageIndex = ref<number>(0);
// 页码
const currentPage = ref<number>(1);

// 单词实体
const data = ref<WordEntity>();
// 当前选择的单词|短语 位置
const dataIndex = ref<number>(0);

async function getWord(query: PageQueryEntity){
    query['type'] =  router.query['id'];
    let result = await httpClient.get(`/word/word`,{
        params: query,
    });
    if(result.status == 200){
        pageIndex.value = 0;
        let resultData = <Result<WordEntity[]>>result.data;
        if(resultData.data.length == 0){
            return false;
        }
        page.value = resultData.data;
        data.value = page.value[pageIndex.value];
        return true;
    }
    return false;
}

// 输入单个字符校验
let inputCheck : Filter = {
    invoke: (keycode, target)=>{
        if('Backspace' == keycode){
            return FilterResult.null;
        }
        if( dataIndex.value == 0 ){
            if(data.value?.word[target.length] == undefined){
                return  FilterResult.preventDefault;
            }
            if( data.value?.word[target.length] != keycode){
                speechSynthesis.stop();
                speechSynthesis.say(data.value?.word.charAt(target.length)+"");
                return FilterResult.exit | FilterResult.preventDefault;
            }
        }else{
            if(data.value?.phrases?.[dataIndex.value - 1].phrase[target.length] == undefined ){
                return  FilterResult.preventDefault;
            }
            if(data.value?.phrases?.[dataIndex.value - 1].phrase[target.length] != keycode){
                speechSynthesis.say(data.value?.phrases?.[dataIndex.value - 1].phrase.charAt(target.length)+"");
                return FilterResult.exit | FilterResult.preventDefault;
            }
        }
        return FilterResult.null;
    },

};
// 输入字符日志
let logFilter: Filter = {
    invoke: (keyCode, target)=>{
        return FilterResult.null;
    }
}
// 回车整行检验
let enterFilter: Filter = {
    invoke: (keyCode, target)=>{
        if(keyCode == 'Enter'){
            if(dataIndex.value == 0){
                console.log(target+":"+ data.value?.word)
                if(target != data.value?.word){
                    console.log(FilterResult.exit | FilterResult.preventDefault)
                    return FilterResult.exit | FilterResult.preventDefault;
                }
            }else{
                console.log(target+":"+ data.value?.phrases?.[dataIndex.value-1].phrase)
                if(target != data.value?.phrases?.[dataIndex.value-1].phrase){
                    console.log(FilterResult.exit | FilterResult.preventDefault);
                    return FilterResult.exit | FilterResult.preventDefault;
                }
            }
        }
        return FilterResult.null;
    }
}

onMounted(async ()=>{
    getWord({})
    say(-1);
    filter.addFilter("one", logFilter);
    filter.addFilter("inputChekc", inputCheck);
    filter.addFilter("enterFilter", enterFilter);
    setTimeout(()=>{
        headerInputDiv.value?.focus();
    },1000)
})

async function keydown(event: KeyboardEvent){
    let filters = filter.getFilter();
    let keys = filters.keys()
    for(let k = keys.next() ; !k.done; k = keys.next() ){
        let ft: Filter = <any>filters.get(<any>k.value);
        let targetValue = (<HTMLDivElement>event.target)?.innerText;
        let filterResult = ft.invoke(event.key, targetValue);
        console.log((filterResult & FilterResult.preventDefault) +" "+ FilterResult.preventDefault)
        if((filterResult & FilterResult.preventDefault) == FilterResult.preventDefault){
            event.preventDefault();
        }
        if((filterResult & FilterResult.exit) == FilterResult.exit){
            return;
        }
    }
    if(event.code == 'Tab'){
        event.preventDefault();
        console.log(dataIndex.value);
        say(dataIndex.value-1);
        return;
    }
    if(event.code == 'Enter'){
        speechSynthesis.stop();
        event.preventDefault();
        if( dataIndex.value < inputDivList.value.length ){
            (inputDivList.value[dataIndex.value]).focus();
                say(dataIndex.value);
                dataIndex.value+=1;
        } else {
            if(page.value && pageIndex.value+1 == page.value?.length){
                if( await getWord({offset: String(currentPage.value+1)})){
                    currentPage.value = parseInt(<any>currentPage.value)+1
                    console.log("ok")
                    dataIndex.value=0;
                    say(-1);
                    return;
                }
            }

        }
        return;
    }
}

function say(wordIndex: number, beforeStop: boolean = true){
    if(beforeStop)
        speechSynthesis.stop();
    if(wordIndex == -1){
        headerInputDiv.value?.focus();
        if(data.value?.word != undefined){
            speechSynthesis.say(data.value?.word);
        }
        let translations = data.value?.translations;
        if( translations != undefined ){
            for(let i in translations){
                let translation = translations[i];
                if(translation.type != undefined)
                    speechSynthesis.say(translation.type);
                if(translation.translation != undefined)
                    speechSynthesis.say(translation.translation);
            }
        }
    }else{
        let phrases = data.value?.phrases?.[wordIndex];
        if(phrases != undefined){
            speechSynthesis.say(phrases.phrase);
            speechSynthesis.say(phrases.translation);
        }
    }
}

</script>

<template>
    <div id="word-content">
        <ul>
            <li>
                <div class="word-content">
                    <span> {{ data?.word }} </span>
                    <template v-for="t in data?.translations">
                        <spen style="text-align: center; display: grid"> {{ t.type }}.{{ t.translation }}</spen>
                    </template>
                </div>
                <div contenteditable="true" class="word-edit-content" ref="headerInputDiv" :key="data?.word" @keydown="keydown" @click="dataIndex = 0; say(-1)"></div>
            </li>

            <li v-for="w,i in data?.phrases" >
                <div class="word-content">
                    <span>{{ w.phrase }}</span>
                    <span> {{ w.translation }} </span>
                </div>
                <div contenteditable="true" class="word-edit-content" @keydown="keydown" ref="inputDivList" @click="dataIndex = i+1; say(i)"></div>
            </li>
        </ul>
        <div style="height: 66px;width: 100%" id="bottom-content">
            <el-form style="max-width: 160px">
                <el-form-item label="当前页" style="color: red;">
                    <el-input  v-model="currentPage" style="width: 65px; margin-right: 3px"  ></el-input>
                    <el-button type="primary"  style="width: 35px" @click="getWord({})" >修改</el-button>
                </el-form-item>
            </el-form>
            
        </div>
    </div>
</template>

<style lang="less" scoped>
#word-content {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-content: center;
    background-color: rgba(131, 131, 131, 0.514);
}

ul {
    display: grid;
    @media (min-width: 450px) {
        grid-template-columns: repeat(1, 250px);
    }
    @media (min-width: 700px) {
        grid-template-columns: repeat(2, 250px);
    }
    @media (min-width: 1050px) {
        grid-template-columns: repeat(3, 250px);
    }
    @media (min-width: 1300px) {
        grid-template-columns: repeat(4, 250px);
    }
    @media (min-width: 1550px) {
        grid-template-columns: repeat(5, 250px);
    }
    @media (min-width: 1800px) {
        grid-template-columns: repeat(6, 250px);
    }
    width: 100%;
    height: calc( 100vh - 96px );
    padding-left:  100px;
    padding-right: 100px;
    justify-content: center;
    align-content: start;
    overflow-y: auto;
    margin-top: 0px;
    margin: 15px 0px;
}

.word-content {
    height: calc( 100% - 66px );
    overflow: auto;
}

li {
    list-style: none;
    display: flex;
    align-content: center;
    justify-content: flex-end;
    flex-wrap: wrap;
    flex-direction: column;
    border-radius: 19px;
    height: 136px;
    overflow: auto;
}

span {
    text-align: center;
    display: block; 
}

.word-edit-content {
    width: 100%;
    height: 45px;
    outline: none;
    border-bottom: 2px  solid rgba(51, 51, 51, 0.753);
    text-align: center;
    line-height: 45px;
    color: green;
}
#bottom-content {
    background-color: rgb(110, 133, 153);
}

::-webkit-scrollbar {
    width: 2px;
    height: 2px;
    background-color: rgb(155, 155, 155);
}
::-webkit-scrollbar-track {
    background-color: rgba(165, 165, 165, 0.671);
    border-radius: 1px; 
}
::-webkit-scrollbar-thumb {
    background-color: #66a0ecad; 
    border-radius: 2px; 
}
::-webkit-scrollbar-button {
    height: 0px;
    width: 0px;

}
</style>